const moment = require('moment'); 
//model 数据层
module.exports = class testModel extends require('./Model') {
// 多条件查找
static findGoodByCon(req) {
    return new Promise((resolve, reject) => {
        let conditions = req.query;
        // console.log(conditions);
        let sql = 'SELECT * FROM baking_good WHERE ';
        let params = [];
        let clauses = [];

        if (conditions.name) {
            clauses.push('name LIKE ?');
            params.push(`%${conditions.name}%`);
        }
        if (conditions.id) {
            clauses.push('id = ?');
            params.push(conditions.id);
        }
        // 其他条件...

        if (clauses.length > 0) {
            sql += clauses.join(' AND ');
        } else {
            sql = 'SELECT * FROM baking_good';
        }

        console.log(sql,params);
        this.query(sql, params)
            .then((r) => {
                console.log(r);
                resolve(r);
            })
            .catch((e) => {
                console.error('error:', e);
                reject(e);
            });
    });
}
// static findGoodByCon(req) {
//     return new Promise((resolve, reject) => {
//         let conditions = req.query;
//         let sql = 'SELECT * FROM baking_good WHERE ';
//         let params = [];

//         let clauses = [];
//         if (conditions.id) {
//             clauses.push('id = ?');
//             params.push(conditions.id);
//         }

//         if (clauses.length > 0) {
//             sql += clauses.join(' AND ');
//         } else {
//             sql = 'SELECT * FROM baking_good';
//         }

//         this.query(sql, params)
//             .then((r) => {
//                 resolve(r);
//             })
//             .catch((e) => {
//                 reject(e);
//             });
//     });
// }


    //修改商品信息
    //注意mysql配置是默认不识别大小写的，可以对mysql字段中的排序规则设置为 utf8mb4_bin 这样mysql中你要修改的字段就可以实现区分大小
    static updateGoodList(req, res) {
        return new Promise((resolve, reject) => {
            let info = req.body
            //sql 语句为 当id是xx的时候，把id修改为xxx
            let sql = 'UPDATE baking_good SET ? WHERE id = ?'
            this.query(sql, [info, info.id])
                .then((r) => {
                    res.send({status:1,message:'ok',successMessage:'修改成功！'})
                })
                .catch((e) => {
                    res.send({status:0,message:'error',errorMessage:'修改失败！'})
                })
        })
    }

    // 删除商品信息
    static deleteGoodList(req, res) {
        return new Promise((resolve, reject) => {
            let { id } = req.body
            let sql = 'DELETE FROM baking_good WHERE id=?'
            this.query(sql, [id])
                .then((r) => {
                    resolve({ message: "id 为 " + id + ' 删除成功！' })
                })
                .catch((e) => {
                    reject({ message: "id 为 " + id + " 删除失败", reason: e })
                })
        })
    }

    // 是否售罄（禁用）
    static disableGood(req, res) { 
        return new Promise((resolve, reject) => {
            //sql 语句为 当name是xx的时候，把name修改为xxx
            let sql = 'update baking_good set status=? where id=?'
            this.query(sql, [req.body.status,req.body.id])
                .then((r) => {
                    resolve({ message: "操作成功" })
                })
                .catch((e) => {
                    reject({ message:"操作失败"})
                })
        })
    }

    // 新增图片
    static addGoodImg(req, res) {
        return new Promise(async (resolve, reject) => {
            const { id } = req.body;
            const file = req.file;

            if (!file) {
                return reject({ status: 400, message: 'No file uploaded.' });
            }

            const formData = new FormData();
            formData.append('file', fs.createReadStream(file.path));

            try {
                const response = await axios.post('http://localhost:3000/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });

                const { url } = response.data;

                const sql = 'UPDATE baking_good SET cover_img = ? WHERE id = ?';
                this.query(sql, [url, id])
                    .then((r) => {
                        resolve({ status: 1, message: 'Image uploaded and updated successfully.', url: url });
                    })
                    .catch((e) => {
                        reject({ status: 500, message: 'Internal server error.', error: e });
                    });
            } catch (error) {
                reject({ status: 500, message: 'Failed to upload image.', error: error });
            }
        });
    }
    // 多条件查找分类及其对应的商品信息
    static getCategoryWithGoodsByCon(req, res) {
        return new Promise((resolve, reject) => {
            let sql = `
            SELECT bc.id AS cate_id, bc.name AS cate_name, bc.remark AS cate_remark, bg.id AS good_id, bg.name AS good_name, bg.cover_img, bg.remark AS good_remark
            FROM baking_cate bc
            LEFT JOIN baking_good bg ON bc.id = bg.cate_id
        `;
            let params = [];

            this.query(sql, params) // 调用基类的 query 方法执行 SQL 语句
                .then((r) => {
                    resolve(r);
                })
                .catch((e) => {
                    reject(e);
                });
        });
    }
}